#
# import os
# os.environ["PYTHONUTF8"] = "1"
import web
import datetime

render = web.template.render('templates/')
db = web.database(dbn='mysql', user='root', port=3308, password='root1234', db='python1')


class index:
    def GET(self):
        return "hello,web.py"


class r:
    def GET(self):
        name = "laoliu,现在时间是" + str(datetime.datetime.now())
        return render.hello(name)


class stu:
    def GET(self):
        if  "sname" in web.input():
            sname = web.input().sname
            stus = db.select("s_student", where="sname like $sname", vars={'sname': '%' + sname + '%'})
            return render.students(stus,sname)
        stus = db.select("s_student")
        return render.students(stus,sname='')

    def POST(self):
        f = web.input()
        sname = f.sname
        gradeid = int(f.gradeid)
        qq = f.qq
        wechat = f.wechat
        sex = f.sex
        telephone = f.telephone
        fromcity = f.fromcity
        enterdate = datetime.datetime.strptime(f.enterdate, "%Y-%m-%d") if f.enterdate else None

        db.insert("s_student", sname=sname, gradeid=gradeid, qq=qq, wechat=wechat, sex=sex, telephone=telephone,
                  fromcity=fromcity, enterdate=enterdate)

        return web.seeother("/stus")  # 重定向


class toadd:
    def GET(self):
        return render.addstudent()


class studel:
    def GET(self, id):
        db.delete("s_student", where="stuno=$id", vars=locals())
        return web.seeother("/stus")
class stuupdate:
    def GET(self):
        stuno=int(web.input().stuno)
        #考虑找不到的问题
        student=db.select("s_student",where="stuno=$stuno",vars=locals())[0]
        return render.updatestudent(student)
    def POST(self):
        f = web.input()
        stuno = int(f.stuno)
        sname = f.sname
        gradeid = int(f.gradeid)
        qq = f.qq
        wechat = f.wechat
        sex = f.sex
        telephone = f.telephone
        fromcity = f.fromcity
        enterdate = datetime.datetime.strptime(f.enterdate, "%Y-%m-%d") if f.enterdate else None
        #update s_student set sname=?,sex=? where stuno=##
        db.update("s_student",where='stuno=$stuno',vars={'stuno': stuno}, sname=sname, gradeid=gradeid, qq=qq, wechat=wechat, sex=sex, telephone=telephone,
                  fromcity=fromcity, enterdate=enterdate)
        return web.seeother("/stus")

urls = ('/', 'index', '/hello', 'r', '/stus', 'stu', '/toadd', 'toadd', '/studel/(\d+)', 'studel','/updatestudent','stuupdate')
if __name__ == '__main__':
    # 8080默认端口
    app = web.application(urls, globals())
    app.run()
